﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;


public partial class NavMeshGenerator : EditorWindow {

	class NavMeshConfig{
		public int tileSize = 32;
		public float agentRedius = 2f;
		public float agentHeight = 2f;
	}

	[UnityEditor.MenuItem("Tools/GenNavMesh")]
	public static void ShowWindow(){
		var win = EditorWindow.GetWindow<NavMeshGenerator> ("Gen", true);
		win.Show ();

	}

	public enum Tools
	{
		Sampler			=	0,
		Recaster,
	}

	const float SCENE_VIEW_TITLE_HEIGHT = 36f;

	private GameObject objMesh = null;

	private NavMeshConfig config = new NavMeshConfig();

	private string name = "scene01";

	private RaycastHit currentHit = new RaycastHit();

	private GameObject goNavMesh = null;

	private int toolSelect = 0;

    private GameObject goPolyEditing = null;

	private GUIContent[] toolContents = new GUIContent[]{
		new GUIContent("采样"),
		new GUIContent("测试")
	};

	private Camera editorCamera;

	void OnEnable ()
	{
		SceneView.onSceneGUIDelegate -= this.OnSceneViewGUI;
		SceneView.onSceneGUIDelegate += this.OnSceneViewGUI;

		if (editorCamera == null) {
			var go = GameObject.FindGameObjectWithTag ("EditorCamera");
			if (go != null) {
				editorCamera = go.GetComponent<Camera> ();
			}
		}
        

    }

	void OnDisable ()
	{
		SceneView.onSceneGUIDelegate -= this.OnSceneViewGUI;
	}


	bool isHit = false;


	void OnSceneViewGUI (SceneView view)
	{
		Vector3 pos = Vector3.zero;
		var currentEvent = Event.current;
		if (currentEvent == null) {
			return;
		}
		var mp = currentEvent.mousePosition;
		pos = new Vector3(mp.x, Screen.height - mp.y - SCENE_VIEW_TITLE_HEIGHT, 0);
		RaycastHit[] hits = null;

		if (view.camera != null) {
			var ray = view.camera.ScreenPointToRay(pos);
			hits = Physics.RaycastAll (ray, 10000f);
		}

		if ((isHit = hits.Length > 0)) {
			currentHit = hits [0];	
		}

        //Tools tool = (Tools)toolSelect;
        //switch (tool) {
        //case Tools.Sampler:
        //	OnSceneViewGUI_Sampler (view, currentEvent);
        //	break;
        //case Tools.Recaster:
        //	OnSceneViewGUI_Recast (view, currentEvent);
        //	break;
        //default:
        //	break;
        //}

        OnSceneGUI_Poly(view);

    }



	void OnGUI()
	{
		GUILayout.BeginVertical ();
		GUILayout.BeginHorizontal ();

		int sel = GUILayout.Toolbar (toolSelect, toolContents);
		//TODO:change event here.
		toolSelect = sel;
		GUILayout.EndHorizontal ();

        //Tools tool = (Tools)toolSelect;
        //switch (tool) {
        //case Tools.Recaster:
        //	DrawRecasterToolGUI ();
        //	break;
        //case Tools.Sampler:
        //	DrawSamplerToolGUI ();
        //	break;
        //}
        if (GUILayout.Button("Create Convex")) {
            convexGenerater = new ConvexGenerater();
        }

        if (convexGenerater != null)
        {
            if (convexGenerater.selectVertex >= 0) {
                var p = convexGenerater.verts[convexGenerater.selectVertex];
                var np = EditorGUILayout.Vector3Field("编辑点:", p);
                if ((p - np).sqrMagnitude > 0.01) {
                    convexGenerater.verts[convexGenerater.selectVertex] = np;
                    convexGenerater.ReHull();
                }
            }

            
        }



        GUILayout.EndVertical ();

	}

	void Handle_DrawTrianglePolys(List<Vector3> verts, Color edgeColor, Color polyColor){
		int i = 0;
		Vector3[] v3 = new Vector3[3]; 
		foreach (var v in verts) {
			v3 [i++] = v;
			if (i == 3) {
				Handles.color = polyColor;
				Handles.DrawAAConvexPolygon (v3[0], v3[1], v3[2]);
				Handles.color = edgeColor;
				Handles.DrawPolyLine (v3[0], v3[1], v3[2]);
				i = 0;
			}
		}
	}


    void ConvertConvexToMesh() {
        var mesh = new Mesh();
        convexGenerater.ToMesh(ref mesh);
        GameObject go = new GameObject("convex");
        var mf = go.GetOrAddComponent<MeshFilter>();
        mf.mesh = mesh;

        go.GetOrAddComponent<MeshRenderer>();
     

    }

    void PaintConvexPoly() {
        if (goPolyEditing == null && (goPolyEditing = GameObject.Find("contex_edition")) == null)
        {
            goPolyEditing = new GameObject("contex_edition");
        }
        var mesh = new Mesh();
        convexGenerater.ToMesh(ref mesh);
        var mf = goPolyEditing.GetOrAddComponent<MeshFilter>();
        mf.mesh = mesh;
        goPolyEditing.GetOrAddComponent<MeshRenderer>();
    }

    ConvexGenerater convexGenerater = null;
    void OnSceneGUI_Poly(SceneView view) {
        if (convexGenerater != null) {
            var e = Event.current;
            if (e.type == EventType.MouseDown && e.button == 0 && e.modifiers == EventModifiers.Shift && isHit)
            {
                int sel = convexGenerater.SelectVertex(currentHit.point);
                if(sel >= 0){
                    convexGenerater.selectVertex = sel;
                }
                else
                {
                    convexGenerater.AddVertex(currentHit.point);
                    PaintConvexPoly();
                }

            }
            bool dirty;
            convexGenerater.OnSceneViewGUI(view, out dirty);
            if (dirty) {
                PaintConvexPoly();
            }
        }
   

    }


}
